package org.liquidByte.trafficMustang.androidApp;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

public class LocationTracker {
	
	public static final long UPDATE_MIN_TIME = 20000;
	public static final float UPDATE_MIN_DISTANCE = 100;

	private static LocationTracker instance;

	public static LocationTracker getInstance() {
		if (LocationTracker.instance == null) {
			LocationTracker.instance = new LocationTracker();
		}
		return instance;
	}
	
	public static void cleanUp() {
		if (LocationTracker.instance != null) {
			LocationTracker.instance.setTracking(false);
			LocationTracker.instance.setLocationListener(null);
			LocationTracker.instance = null;
		}
	}

	private LocationManager locationManager;
	private LocationListener locationListener;
	private boolean tracking;
	
	protected LocationTracker() {
		this.tracking = false;
	}

	protected LocationManager getLocationManager() {
		if (this.locationManager == null) {
			this.locationManager = (LocationManager)App.getInstance().getSystemService(Context.LOCATION_SERVICE);
		}
		return this.locationManager;
	}
	
	public boolean isTracking() {
		return tracking;
	}
	public void setTracking(boolean tracking) {
		if (this.tracking != tracking) {
			this.tracking = tracking;
			if (this.locationListener != null) {
				if (tracking) {
					this.registerUpdates();
				} else {
					this.unregisterUpdates();
				}
			}
		}
		this.tracking = tracking;
	}
	public void setLocationListener(LocationListener value) {
		if (this.locationListener != null && this.isTracking()) {
			this.unregisterUpdates();
		}		
		if (value != null && this.isTracking()) {
			this.locationListener = value;
			this.registerUpdates();
		} else {
			this.locationListener = value;
		}
	}
	
	public Location getLastKnown() {
		return this.getLocationManager().getLastKnownLocation(LocationManager.GPS_PROVIDER);
	}
	
	private void registerUpdates() {
		this.getLocationManager().requestLocationUpdates(LocationManager.GPS_PROVIDER, UPDATE_MIN_TIME, UPDATE_MIN_DISTANCE, this.locationListener);
	}
	
	private void unregisterUpdates() {
		this.getLocationManager().removeUpdates(this.locationListener);
	}
}
